package com.mybatis.core;

import com.mybatis.domain.User;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author yangjian
 */
public class MapperProxyFactory implements InvocationHandler {
  @Override
  public Object invoke(Object proxy, Method method, Object[] args) throws Throwable
  {
    if (!method.isAnnotationPresent(Select.class)) {
      return null;
    }
    // 获取 @Select 注解
    Select annotation = method.getAnnotation(Select.class);
    // 获取 SQL 语句模板
    String sql = annotation.value();
    // 解析 SQL 语句
    if (null != args) {
      sql = sql.replace("#{id}", "?");
    }
    System.out.println("SQL: " + sql);
    // 将 SQL 推送到 JDBC 去执行
    // 获取数据库连接
    Connection connection = DatasourceFactory.getConnection();
    // 获取预处理对象
    PreparedStatement stmt = connection.prepareStatement(sql);
    ResultSet res;
    if (null != args) {
      // 绑定参数
      stmt.setString(1, args[0].toString());
      // 执行sql
      res = stmt.executeQuery();
    } else {
      res = stmt.executeQuery(sql);
    }

    Class<?> returnType = method.getReturnType();
    if (returnType.isAssignableFrom(List.class)) {
      return selectList(res);
    } else {
      return selectOne(res);
    }
  }

  // 返回单条数据
  public User selectOne(ResultSet res) throws SQLException
  {
    User user = new User();
    while (res.next()) {
      user.setId(res.getInt("id"));
      user.setName(res.getString("name"));
    }
    return user;
  }

  // 返回列表
  public List<User> selectList(ResultSet res) throws SQLException
  {
    List<User> list = new ArrayList<>();
    while (res.next()) {
      User user = new User();
      user.setId(res.getInt("id"));
      user.setName(res.getString("name"));
      list.add(user);
    }
    return list;
  }
}
